package models

import (
	"fly/schema"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
)

type SysRole struct {
	BaseModel
	Name   string `orm:"column(name);description(角色名称)"`
	Code   string `orm:"column(code);description(角色编码)"`
	Remark string `orm:"column(remark);description(备注)"`
	DeptId int64  `orm:"column(dept_id);description(部门ID)"`
}

func init() {
	orm.RegisterModel(new(SysRole))
}

// SearchField 定义模型的可搜索字段
func (*SysRole) SearchField() []string {
	return []string{"name", "code"}
}

// WhereField 定义模型可作为条件的字段
func (*SysRole) WhereField() []string {
	return []string{"id", "status", "name", "code"}
}

func (m *SysRole) TableName() string {
	return "sys_role"
}

// AddSysRole insert a new SysRole into database and returns
// last inserted Id on success.
func AddSysRole(m *SysRole, userId int64) (id int64, err error) {
	o := orm.NewOrm()
	m.Creator = userId
	m.Updater = userId
	id, err = o.Insert(m)
	return
}

// GetSysRoleById retrieves SysRole by Id. Returns error if
// Id doesn't exist
func GetSysRoleById(id int64) (v *SysRole, err error) {
	o := orm.NewOrm()
	v = &SysRole{BaseModel: BaseModel{Id: id}}
	if err = o.QueryTable(new(SysRole)).Filter("id", id).RelatedSel().One(v); err == nil {
		return v, nil
	}
	return nil, err
}

// UpdateSysRoleById updates SysRole by Id and returns error if
// the record to be updated doesn't exist
func UpdateSysRoleById(m *SysRole, userId int64) (err error) {
	o := orm.NewOrm()
	v := SysRole{BaseModel: BaseModel{Id: m.Id}}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		m.Updater = userId
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

// DeleteSysRole deletes SysRole by Id and returns error if
// the record to be deleted doesn't exist
func DeleteSysRole(id int64) (err error) {
	o := orm.NewOrm()
	v := SysRole{BaseModel: BaseModel{Id: id}}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&SysRole{BaseModel: BaseModel{Id: id}}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}

// DestroySysRole Destroy SysRole by Id and returns error
func DestroySysRole(id int64, userId int64) (err error) {
	o := orm.NewOrm()
	v := SysRole{BaseModel: BaseModel{Id: id}}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		v.Status = schema.StatusDelete
		v.Updater = userId
		var num int64
		if num, err = o.Update(v, "updater", "status"); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}
